package com.hqyj.onlineExamination.modules.common.service.impl;

import com.hqyj.onlineExamination.modules.common.entity.ImageType;
import com.hqyj.onlineExamination.modules.common.entity.ResourceConfigBean;
import com.hqyj.onlineExamination.modules.common.entity.ResultEntity;
import com.hqyj.onlineExamination.modules.common.service.ImageService;
import com.hqyj.onlineExamination.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

//把文件按照类型分文件夹进行储存
//把文件写到绝对路径，把相对路径传给前端
@Service
public class ImageServiceImpl implements ImageService {

    private final static Logger LOGGER = LoggerFactory.getLogger(ImageServiceImpl.class);

    @Value("${artifactId}")
    private String artifactId;

    @Autowired
    private ResourceConfigBean resourceConfigBean;

    //参数：上传的文件、文件的类型
    @Override
    public ResultEntity<String> uploadImage(MultipartFile image, String type) {
        // 检查图片是否为空 不能用null
        if (image.isEmpty()) {
            return new ResultEntity<>(ResultEntity.ResultStatus.FAILED.status,
                    "Image is null.");
        }
        // 检查 file 是否是图片
        if (!FileUtil.isImage(image)) {
            return new ResultEntity<>(ResultEntity.ResultStatus.FAILED.status,
                    "The file is not image.");
        }

        // 根据前端传入的type类型，获取图片枚举类型
        ImageType imageType = ImageType.getImageTypeByName(type);

        // 确定目标地址(目标文件夹)的绝对路径
        String destFolderPath = String.format("%s%s/%s",
                System.getProperty("os.name").toLowerCase().startsWith("win") ?
                        resourceConfigBean.getLocalPathForWindow() ://本地根目录
                        resourceConfigBean.getLocalPathForLinux(),
                artifactId,//项目名称
                imageType.name);//图片类型
        File destFolder = new File(destFolderPath);
        //创建文件夹
        if (!destFolder.exists()) {
            destFolder.mkdirs();
        }

        //创建文件名
        String fileName = String.format("%s.%s",
                System.currentTimeMillis(),
                FileUtil.getFileType(image.getOriginalFilename()));

        //图片绝对路径
        String absolutePath = String.format("%s/%s", destFolderPath, fileName);

        // 获取目标文件相对路径
        String relatedPath = String.format("%s%s/%s/%s",
                resourceConfigBean.getResourcePath(),
                artifactId,
                imageType.name,
                fileName);

        LOGGER.debug("absolutePath: " + absolutePath);
        LOGGER.debug("relatedPath: " + relatedPath);

        try {
            //移植图片文件
            image.transferTo(new File(absolutePath));
            //修改文件大小，根据设置的枚举类型的尺寸来变化图片的尺寸
            FileUtil.changeImageSize(absolutePath, absolutePath, imageType.maxWidth, imageType.maxHeight);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return new ResultEntity<>(ResultEntity.ResultStatus.FAILED.status, "File upload error.");
        }
        //返回正确结果
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.status, "File upload success.", relatedPath);
    }
}
